<?php


namespace app\service;


use app\Constants;
use think\facade\Db;
use think\facade\Log;
use think\facade\Queue;

class settleService
{
    public function settleConfirmOrder($data){
        $order_uid=$data["id"];
        $info=Db::table("zft_order_success")->where("uid",$data["id"])->find();
        if(empty($info)){
            print("<info>ZftSettleConfirmOrder job Data is: 订单不存在</info> \n");
            return (new RedisQueueService())->push("ZftSettleConfirmOrderFailed",$data["id"]." 订单不存在");
            return false;

        }
        $propertyZftInfo=(new propertyService())->propertyZftByComId($info["community_id"]);
        if(empty($propertyZftInfo)){

            print("<info>ZftSettleConfirmOrder job Data is: 直付通配置为空</info> \n");
            return (new RedisQueueService())->push("ZftSettleConfirmOrderFailed",$data["id"]." 直付通配置为空");
            return false;
        }
        //$api=new zftService();
        $api=new alipayWapService();
        $amount=round($propertyZftInfo["taxrate"]*$info["order_money"],2);

        $royalty_parameters=array(
            'royalty_type'=>'transfer',//'',
            'trans_in_type'=>'loginName',//收入方账户类型userId
            'trans_in'=>$propertyZftInfo["binding_alipay_logon_id"],//收入方账户\linan2421@163.com  2088070839250462
            'amount'=>$info["order_money"],//分账金额
        );
        $data= array(
            'out_trade_no'=> $info["out_trade_no"],
            'trade_no'=>$info["trade_no"],
            'royalty_parameters'=>$royalty_parameters,
        );
        $result = $api->settleComfirm(json_encode($data));
        Log::write($result);
        $add["result_code"]=$result->code;
        $add["order_uid"]=$info["uid"];
        $add["create_time"]=date("Y-m-d H:i:s");
        if($result->code=="10000"){
            $add["result_msg"]="成功";
            $add["out_request_no"]=$result->out_request_no;
            $add["trade_no"]=$result->trade_no;
            $add["settle_amount"]=$result->settle_amount;
            //$add["source"]="queue";
            $add["community_id"]=$info["community_id"];
            $add["trans_in_type"]=$royalty_parameters["trans_in_type"];
            $add["trans_in"]=$royalty_parameters["trans_in"];
            Db::table("zft_log_settle_confirm")->insert($add);
            $jobData       	  = [ 'id' => $order_uid ] ;
            $this->settleOrder($jobData);
        }else{
            $add["out_request_no"]=$info["out_trade_no"];
            $add["trade_no"]=$info["trade_no"];
            $add["result_msg"]=$result->sub_msg;
            $add["sub_code"]=$result->sub_code;
            //$add["source"]="queue";
            $add["community_id"]=$info["community_id"];
            $add["trans_in_type"]=$royalty_parameters["trans_in_type"];
            $add["trans_in"]=$royalty_parameters["trans_in"];
            Db::table("zft_log_settle_confirm_fail")->insert($add);

            $jobQueueName  	  = "app\job\ZftSettleConfirmOrder";
            $jobData       	  = [ 'id' =>$order_uid ] ;
            $res= \think\facade\Queue::push($jobQueueName,$jobData);

            $queueName  	  = "app\job\ZftNotifyUrl";
            $jobData       	  = [ 'id' =>$info["id"] ,"order_uid"=>$info["uid"],"alipay_notify_con"=>$info["alipay_notify_con"],"community_id"=>$info["community_id"]] ;
            $resu= \think\facade\Queue::push($queueName,$jobData);
            return false;
        }
        return true;
    }
    public function settleOrder($data){
        $info=Db::table("zft_order_success")->where("uid",$data["id"])->find();
        Log::write($info);
        if(empty($info)){
            return (new RedisQueueService())->push("ZftSettleOrderFailed",$data["id"]);
        }
        if($info["settle_status"]==1){
            return true;
        }
        //查询该账单是否已经结算
        $propertyZftInfo=(new propertyService())->propertyZftByComId($info["community_id"]);
        if(empty($propertyZftInfo)){
            print("<info>Hello Job Started. job Data is: 直付通配置为空</info> \n");
            return json(['info' => '直付通配置为空']);
        }
        //$api=new zftService();
        $api=new alipayWapService();
        $amount=round($propertyZftInfo["taxrate"]*$info["order_money"],2);


        $royalty_parameters=array(
            'royalty_type'=>'transfer',//'loginName',
            'trans_in_type'=>'loginName',//收入方账户类型
            'trans_in'=>env("APP.royalty_trans_in"),//'aliwykd@163.com',//收入方账户\linan2421@163.com
            'amount'=>$amount,//分账金额
        );
        $data= array(
            'out_trade_no'=> $info["trade_no"],
            'trade_no'=>$info["trade_no"],
            'royalty_parameters'=>$royalty_parameters,
        );

        $result = $api->settle(json_encode($data));
        $add_log["result_code"]=$result->code;
        $add_log["order_uid"]=$info["uid"];
        $add_log["create_time"]=date("Y-m-d H:i:s");
        $add_log["source"]="";
        if($result->code==10000){
            $settle["community_id"]=$info["community_id"];
            $settle["trade_no"]=$info["trade_no"];
            $settle["order_uid"]=$info["uid"];
            $settle["order_money"]=$info["pay_money"];
            $settle["settle_money"]=$amount;
            $settle["community_name"]=$info["community_name"];
            $settle["settle_no"]=$result->settle_no;
            $settle["createTime"]=time();
            $settle["taxrate"]=$propertyZftInfo["taxrate"];
            $settle["ctime"]=date("Y-m-d H:i:s");
            $settle["receive_account"]=$propertyZftInfo["binding_alipay_logon_id"];
            $settle["debit_account"]=env("APP.royalty_trans_in");
            $settle["gate_id"]=$info["gate_id"];
            $settle["gate_name"]=$info["gate_name"];
            //查询zft_settle_order是否有订单,如果有
            $settle_order=Db::table("zft_settle_order")
                ->where("order_uid",$info["uid"])
                ->find();
            if(empty($settle_order)){
                $resultId=Db::table("zft_settle_order")->insertGetId($settle);
            }else{
                $resultId=$settle_order["id"];
            }

            $add_log["out_request_no"]=$data["out_trade_no"];
            $add_log["trade_no"]=$data["trade_no"];
            $add_log["settle_no"]=$settle["settle_no"];
            Db::table("zft_log_settle_order")->insert($add_log);

            Db::table("zft_order_success")->where("uid",$info["uid"])->update(["settle_status"=>1]);
//            $jobQueueName  	  = "app\job\ZftSettleQueryOrder";
//            $jobData       	  = [ 'id' => $resultId ] ;
//            $res=Queue::push($jobQueueName,$jobData);

        }else{
            $add_log["result_msg"]=$result->sub_msg;
            $add_log["sub_code"]=$result->sub_code;
            $add_log["out_request_no"]=$info["out_trade_no"];
            $add_log["trade_no"]=$info["trade_no"];
            $logId=Db::table("zft_log_settle_order")->insertGetId($add_log);
            $settle["community_id"]=$info["community_id"];
            $settle["trade_no"]=$info["trade_no"];
            $settle["order_uid"]=$info["uid"];
            $settle["order_money"]=$info["pay_money"];
            $settle["settle_money"]=$amount;
            $settle["community_name"]=$info["community_name"];
            $settle["createTime"]=time();
            $settle["ctime"]=date("Y-m-d H:i:s");
            $settle["fail_msg"]=$add_log["result_msg"];
            $settle["log_settle_order_id"]=$logId;
            $settle["sub_code"]=$result->sub_code;
            $settle["out_trade_no"]=$info["out_trade_no"];
            if(in_array($add_log["sub_code"], Constants::$settleErrorCode)){
                (new communityZftGateService())->setPayStatus($info["gate_id"],"0");
                $settle["close_pay_status"]="1";
            }
            if(in_array($result->sub_code, Constants::$settleRepeatCode)){
                $jobQueueName  	  = "app\job\ZftSettleConfirmOrder";
                $jobData       	  = [ 'id' =>$info["uid"] ] ;
                $res= \think\facade\Queue::push($jobQueueName,$jobData);
            }
            $res=Db::table("zft_settle_order_fail")->insert($settle);
        }
        print("<info>Hello Job Started. job Data is: ".var_export($result,true)."</info> \n");


        return true;
    }
    public function settleOrderQuery($data){
        $info=Db::table("zft_settle_order")->where("id",$data["id"])->find();
        Log::write($info,"settleOrderQuery");
        Log::write($data,"settleOrderQueryParams");
        if(!empty($info)){
            $query["settle_no"]=$info["settle_no"];//$info["settle_no"];
            //$api=new zftService();
            $api=new alipayWapService();
            $result = $api->settleQuery(json_encode($query));


            $add_log["result_code"]=$result->code;
            $add_log["settle_order_id"]=$info["id"];
            $add_log["settle_no"]=$info["settle_no"];
            $add_log["create_time"]=date("Y-m-d H:i:s");
            if($result->code==10000){
                $add_log["result_msg"]=$result->msg;
                $add_log["out_request_no"]=$result->out_request_no;
                $add_log["operation_dt"]=$result->operation_dt;
                if($result->royalty_detail_list){
                    $add_log["royalty_detail_list"]=json_encode($result->royalty_detail_list);
                }

                Db::table("zft_settle_order")->where("id",$info["id"])->update(["status"=>1]);
                Db::table("zft_order_success")->where("uid",$info["order_uid"])->update(["settle_status"=>1]);
                Db::table("zft_log_settle_order_query")->insert($add_log);


            }else{
                $add_log["result_msg"]=$result->msg;
                $add_log["sub_code"]=$result->sub_code;

                Db::table("zft_log_settle_order_query")->insert($add_log);
            }
        }
    }


}